package com.pww.movie.utils;

import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Component
@AllArgsConstructor
public class UploadBase64Image2MinioUtil {

    private final MinioClient minioClient;

    public String uploadBase64Image2Minio(String base64Str, String bucketName, String endpoint) throws Exception {
        //提取文件名
        String[] parts = base64Str.split(",");
        if (parts.length != 2) {
            throw new IllegalArgumentException("无效的Base64字符串");
        }
        // data:image/jpeg;base64
        String header = parts[0];
        // image/jpeg
        String mimeType = header.substring(header.indexOf(":") + 1, header.indexOf(";"));
        // jpeg
        String ext = mimeType.substring(mimeType.indexOf("/") + 1);
        MultipartFile multipartFile = Base64ToMultipart.base64ToMultipart(base64Str, UUID.randomUUID().toString() + "." + ext);
        String objectName = UUID.randomUUID().toString() + "_cover" + "." + ext;
        String url = MinioUploadUtil.uploadFile(minioClient, bucketName, multipartFile, objectName, endpoint);
        return url;
    }
}
